import router from "@/router";
import { usePermissionStore, useAppStore, useUserStore } from "@/store";
import NProgress from "@/utils/nprogress";
import { getToken } from "@/utils/session";

export function setupPermission() {
  // 白名单路由
  const whiteList = ["/login"];

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken = getToken();
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/" });
        NProgress.done();
      } else {
        // 已登录但是Vue路由未初始化
        const permissionStore = usePermissionStore();
        const hasInit = permissionStore.hasInit();
        const appStore = useAppStore();

        appStore.changeShowSideBar(to.meta?.showSideBar);

        if (hasInit) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            from.name ? next({ name: from.name }) : next("/404");
            return;
          } else {
            next();
            return;
          }
        }

        const userStore = useUserStore();
        try {
          const { menuList } = await userStore.getUserInfo();
          const accessRoutes = await permissionStore.generateRoutes(menuList);
          accessRoutes.forEach((route) => {
            router.addRoute(route);
          });

          next({ ...to, replace: true });
        } catch (error) {
          // 移除 token 并跳转登录页
          await userStore.resetToken();
          next(`/login?redirect=${to.path}`);
          console.log("路由配置出错了！", error);
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
